package com.shen.pc;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JucPC {
    public static void main(String[] args) {
        Data02 data=new Data02();
        new Thread(
                ()->{
                    for (int i = 0; i <10 ; i++) {
                        try {
                            data.increment();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                ,"A"  ).start();

        new Thread(
                ()->{
                    for (int i = 0; i <10 ; i++) {
                        try {
                            data.decrement();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                ,"B"  ).start();
        new Thread(
                ()->{
                    for (int i = 0; i <10 ; i++) {
                        try {
                            data.increment();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                ,"C"  ).start();

        new Thread(
                ()->{
                    for (int i = 0; i <10 ; i++) {
                        try {
                            data.decrement();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                ,"D"  ).start();
    }
}



//判断 等待 业务 通知
class Data02{
    final Lock lock=new ReentrantLock();
    final Condition condition = lock.newCondition();
    private int number=0;


    //+1
    public  void increment() throws InterruptedException {
        lock.lock();//加锁
        try {
            while (number!=0){//判断
                //等待
                condition.await();
            }
            number++;//业务
            System.out.println(Thread.currentThread().getName()+"==>"+number);
            //通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); //解锁
        }

    }

    //-1
    public  void decrement() throws InterruptedException {
        lock.lock();//加锁
        try {
            while(number==0){//判断
                //等待c
                condition.await();
            }
            number--;//业务
            System.out.println(Thread.currentThread().getName()+"==>"+number);
            //通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }
    }
}